<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Product extends Backend
{
    protected $navTitle = "product";

    public $files = '';

    public function __construct()
    {
        parent::__construct();

        $this->ProductModel = model('Product.Product');
        $this->TypeModel = model('Product.Type');
    }

    // TODO 商品列表
    public function index()
    {
        //TODO 查询产品数据
        $productList = $this->ProductModel->with('type')->paginate(10);
        $flag = [
            1 => '新品',
            2 => '热销',
            3 => '推荐',
        ];
        // TODO 商品分类
        $typeList = $this->TypeModel->select();

        return $this->fetch('', [
            'productList' => $productList,
            'typeList' => $typeList,
            'navTitle' => $this->navTitle,
            'flag' => $flag,

        ]);
    }

    // TODO 商品搜索
    public function search()
    {
        // TODO 商品分类
        $typeList = $this->TypeModel->select();

        $name = $this->request->param('name', '');

        $typeid = $this->request->param('typeid', 0);

        $flag = $this->request->param('flag', 0);

        $where = [];
        // halt($formData);

        if ($name == null && $typeid == 0 && $flag == 0) $this->error('请输入查询的条件');

        if ($name != '') {
            $where['name'] = ['like', "%$name%"];
        }
        if ($typeid != 0) {
            $where['typeid'] = $typeid;
        }
        if ($flag != 0) {
            $where['flag'] =  $flag;
        }
        // halt($where);
        $productList = $this->ProductModel
            ->where($where)
            ->paginate(10);

        return $this->fetch('index', [
            'productList' => $productList,
            'typeList' => $typeList,
            'navTitle' => $this->navTitle
        ]);
    }

    public function uploads()
    {
        if ($this->request->isPost()) {
            if (isset($_FILES['file']) && $_FILES['file']['size'] > 0) {
                $file = upload('file');

                if ($file['code'] == 0) $this->error('上传失败,' . $file['msg']);

                $id = build_id();
                $data = [
                    'status' => 200,
                    'info' => "成功",
                    "class" => "success",
                    "id" => $id,
                    "picurl" => $file['data'],
                ];
                // halt($data);
                // return $file['data'];
                return json_encode($data);
            }
        }
    }

    public function del_img()
    {
        $url = $this->request->param('url', '');

        if (empty($url)) {
            $this->error('图片地址未知，删除失败');
        } else {
            @is_file('.' . $url) && unlink('.' . $url);
            $this->success('图片删除成功');
        }
    }

    // TODO 添加商品
    public function add()
    {
        $TypeList = $this->TypeModel->select();
        $flag = [
            1 => '新品',
            2 => '热销',
            3 => '推荐',
        ];

        if ($this->request->isPost()) {
            $formData = $this->request->param();

            $thumbs = trim($formData['thumbs'], ',');

            $cover = upload('cover');

            if ($cover['code'] == 0) $this->error('封面图上传失败，' . $cover['msg']);

            $content = str_replace('，', ',', $formData['content']);

            $content = rtrim($content, ',');

            $content = explode(',', $content);

            $content = ContentTemp($content);

            // TODO 封装
            $data = [
                'name' => $formData['name'],
                'price' => $formData['price'],
                'stock' => $formData['stock'],
                'typeid' => $formData['typeid'],
                'cover' => $cover['data'],
                'thumbs' => $thumbs,
                'flag' => $formData['flag'],
                'content' => $content
            ];

            $result = $this->ProductModel->save($data);

            if ($result === FALSE) {
                @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);

                $thumbsArr = explode(',', $thumbs);

                foreach ($thumbsArr as $item) {
                    @is_file('.' . $item) && unlink('.' . $item);
                }

                $this->error('添加商品失败,' . $this->ProductModel->getError());
            } else {
                $this->success('添加商品成功', url('/admin/product/index'));
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'TypeList' => $TypeList,
            'flag' => $flag,
        ]);
    }

    // TODO 修改商品
    public function edit()
    {
        $TypeList = $this->TypeModel->select();
        $flag = [
            1 => '新品',
            2 => '热销',
            3 => '推荐',
        ];

        $pid = $this->request->param('id', '');

        $product = $this->ProductModel->find($pid);

        if (!$product) $this->error('商品不存在');

        $o_thumbs = explode(',', $product['thumbs']);
        $n_thumbs = [];
        foreach ($o_thumbs as $key => $value) {
            $temp = 'thumb' . ($key + 1);
            $n_thumbs[$temp] = $value;
        }
        $o_thumbs = $n_thumbs;
        // halt($n_thumbs);

        if ($this->request->isPost()) {
            // TODO 接收参数
            $formData = $this->request->param();

            $product = $this->ProductModel->find($formData['id']);

            if (!$product) $this->error('商品不存在');

            // TODO 内容更新
            $content = str_replace('，', ',', $formData['content']);

            $content = rtrim($content, ',');

            $content = explode(',', $content);

            $content = ContentTemp($content);

            // TODO 封装参数
            $data = [
                'id' => $pid,
                'name' => $formData['name'],
                'price' => $formData['price'],
                'stock' => $formData['stock'],
                'typeid' => $formData['typeid'],
                'flag' => $formData['flag'],
                'content' => $content,
            ];

            // TODO 更新的图集
            $u_thumbs = [];

            // TODO 所有上传的图片
            $files = [];

            // TODO 图集更新后被替换的路径
            $d_thumbs = [];

            if (!empty($_FILES)) {
                foreach ($_FILES as $key => $value) {
                    if ($_FILES[$key]['error'] || $_FILES[$key]['size'] <= 0) continue;

                    $file = upload($key);
                    $files[] = $file;

                    if ($key == 'cover') {
                        if ($file['code'] == 0) $this->error('封面图上传失败，' . $file['msg']);

                        $data['cover'] = $file['data'];
                    } else {
                        $u_thumbs[$key] = $file['data'];
                    }
                }

                // ! bug 只更换一张图集，原本的地址是否会被覆盖
                foreach ($u_thumbs as $key => $value) {
                    $n_thumbs[$key] = $value;
                }

                $thumbs = implode(',', $n_thumbs);

                $data['thumbs'] = $thumbs;
            }

            // TODO 获取被遗弃的图集路径
            foreach ($n_thumbs as $key => $value) {
                if ($n_thumbs[$key] != $o_thumbs[$key]) {
                    $d_thumbs[] = $o_thumbs[$key];
                }
            }

            $result = $this->ProductModel->isUpdate()->save($data);

            if ($result === FALSE) {
                if (!empty($_FILES) && !empty($files)) {
                    foreach ($files as $item) {
                        @is_file('.' . $item['data']) && @unlink('.' . $item['data']);
                    }
                }
                $this->error('商品更新失败' . $this->ProductModel->getError());
            } else {
                if (!empty($_FILES) && !empty($files)) {
                    // TODO 删除封面图
                    if (isset($data['cover'])) {
                        @is_file('.' . $product['cover']) && @unlink('.' . $product['cover']);
                    }
                    // TODO 删除被遗弃的图集
                    if (!empty($d_thumbs)) {
                        foreach ($d_thumbs as $item) {
                            @is_file('.' . $item) && @unlink('.' . $item);
                        }
                    }
                }
                $this->success('商品更新成功', url('admin/product/index'));
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'product' => $product,
            'TypeList' => $TypeList,
            'flag' => $flag,
        ]);
    }

    // TODO 软删除商品
    public function delete()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action', '');

            if ($action == 'del') {
                $pid = $this->request->param('pid', '');

                $product = $this->ProductModel->find($pid);

                if (!$product) $this->error('商品不存在');

                $result = $this->ProductModel->destroy($pid);

                $result === FALSE ? $this->error('删除失败') : $this->success('删除成功', url('admin/product/index'));
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $formData = $this->request->param();
                // TODO 转存idArr
                $idArr = $formData['idArr'];

                $result = $this->ProductModel->destroy($idArr);

                $result === FALSE ? $this->error('删除失败') : $this->success('删除成功', url('admin/product/index'));
            }
        }
    }

    // TODO 商品回收站
    public function pappman()
    {
        $productList = $this->ProductModel->onlyTrashed()->paginate(10);

        $formData = $this->request->param();

        if ($this->request->isAjax()) {
            $action = $this->request->param('action');

            if ($action == 'return') {
                $pid = $this->request->param('pid', '');

                $product = $this->ProductModel->onlyTrashed()->find($pid);

                if (!$product) $this->error('商品不存在');

                $product->restore() === FALSE ? $this->error('商品还原失败') : $this->success('商品还原成功');
            }

            if ($action == 'returns') {
                // TODO 转存idArr
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $result = $this->ProductModel->onlyTrashed()->whereIn('id', $idArr)->update(['deletetime' => null]);

                $result === FALSE ? $this->error('商品还原失败,' . $this->ProductModel->getError()) : $this->success('商品还原成功');
            }

            if ($action == 'del') {
                $pid = $this->request->param('pid', '');

                $product = $this->ProductModel->onlyTrashed()->find($pid);

                $thumbs = explode(',', $product['thumbs']);

                if (!$product) $this->error('商品不存在');

                $result = $this->ProductModel->destroy($pid, true);

                if ($result === FALSE) {
                    $this->error('商品删除失败,' . $this->ProductModel->getError());
                } else {
                    @is_file('.' . $product['cover']) && unlink('.' . $product['cover']);
                    foreach ($thumbs as $item) {
                        @is_file('.' . $item) && unlink('.' . $item);
                    }
                    $this->success('商品删除成功');
                }
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $productList = $this->ProductModel->onlyTrashed()->whereIn('id', $idArr)->select();

                $result = $this->ProductModel->destroy($idArr, true);

                if ($result === FALSE) {
                    $this->error('商品删除失败' . $this->ProductModel->getError());
                } else {
                    foreach ($productList as $item) {
                        @is_file('.' . $item['cover']) && unlink('.' . $item['cover']);

                        $thumbs = explode(',', $item['thumbs']);
                        foreach ($thumbs as $items) {
                            @is_file('.' . $items) && unlink('.' . $items);
                        }
                    }
                    $this->success('商品删除成功');
                }
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'productList' => $productList
        ]);
    }

    // TODO 商品分类列表
    public function type()
    {
        // TODO 商品分类
        $typeList = $this->TypeModel->paginate(10);

        if ($this->request->isPost()) {
            $formData = $this->request->param();
            // halt($formData);
            $where = [];
            if ($formData['search_field'] == 'name') {
                $where['name'] = ['like', "%{$formData['keyword']}%"];

                $typeList = $this->TypeModel->where($where)->paginate(10);
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'typeList' => $typeList
        ]);
    }

    // TODO 修改商品分类信息
    public function edittype()
    {
        // TODO 获取typeid
        $typeid = $this->request->param('typeid');

        $type = $this->TypeModel->find($typeid);

        if (!$type) $this->error('分类不存在');

        // TODO 修改
        if ($this->request->isPost()) {
            // TODO 接收参数
            $formData = $this->request->param();
            // halt($formData);
            $data = [
                'id' => $typeid,
                'name' => $formData['name'],
                'weigh' => $formData['weigh']
            ];

            if (!empty($_FILES)) {
                $cover = upload('cover');

                if ($cover['code'] == 0) $this->error('上传失败，' . $cover['msg']);

                $data['cover'] = $cover['data'];
            }

            $result = $this->TypeModel->isUpdate()->save($data);

            if ($result === FALSE) {
                @is_file('.' . $data['cover']) && unlink('.' . $type['cover']);
                $this->error('分类更新失败');
            } else {
                @is_file('.' . $type['cover'] && '.' . $type['cover']);
                $this->success('分类更新成功');
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'type' => $type,
        ]);
    }

    // TODO 添加商品分类
    public function addtype()
    {
        // TODO 添加分类
        if ($this->request->isPost()) {
            $formData = $this->request->param();

            $data = [
                'name' => $formData['name'],
                'weigh' => $formData['weigh']
            ];

            if (!empty($_FILES)) {
                $cover = upload('cover');

                if ($cover['code'] == 0) $this->error('上传失败，' . $cover['msg']);

                $data['cover'] = $cover['data'];
            }

            $result = $this->TypeModel->save($data);

            $result === FALSE ? $this->error('添加失败，' . $this->TypeModel->getError()) :
                $this->success('添加成功', url('admin/product/type'));
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
        ]);
    }

    // TODO 商品分类软删除
    public function tdelete()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action');

            if ($action == 'del') {
                $tid = $this->request->param('tid');

                $type = $this->TypeModel->find($tid);

                if (!$type) $this->error('分类不存在');

                $result = $this->TypeModel->destroy($tid);

                $result === FALSE ? $this->error('商品分类移入回收站失败') : $this->success('商品分类移入回收站成功');
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $formData = $this->request->param();
                // TODO 转存idArr
                $idArr = $formData['idArr'];
                // halt($idArr);
                $result = $this->TypeModel->destroy($idArr);

                $result === FALSE ? $this->error('商品分类移入回收站失败') : $this->success('商品分类移入回收站成功');
            }
        }
    }

    // TODO 商品分类回收站
    public function tappman()
    {
        $typeList = $this->TypeModel->onlyTrashed()->paginate(10);

        $formData = $this->request->param();

        if ($this->request->isAjax()) {
            $action = $this->request->param('action');

            if ($action == 'return') {
                $typeid = $this->request->param('typeid', '');

                $type = $this->TypeModel->onlyTrashed()->find($typeid);

                if (!$type) $this->error('分类不存在');

                $type->restore() === FALSE ? $this->error('分类还原失败') : $this->success('分类还原成功');
            }

            if ($action == 'returns') {
                // TODO 转存idArr
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $result = $this->TypeModel->onlyTrashed()->whereIn('id', $idArr)->update(['deletetime' => null]);

                $result === FALSE ? $this->error('分类还原失败,') : $this->success('分类还原成功');
            }

            if ($action == 'del') {
                $typeid = $this->request->param('typeid', '');

                $type = $this->TypeModel->onlyTrashed()->find($typeid);

                if (!$type) $this->error('分类不存在');

                $result = $this->TypeModel->destroy($typeid, true);

                if ($result === FALSE) {
                    $this->error('分类删除失败');
                } else {
                    @is_file('.' . $type['cover']) && unlink('.' . $type['cover']);
                    $this->success('分类删除成功');
                }
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $typeList = $this->TypeModel->onlyTrashed()->whereIn('id', $idArr)->select();

                $result = $this->TypeModel->destroy($idArr, true);

                if ($result === FALSE) {
                    $this->error('分类删除失败');
                } else {
                    foreach ($typeList as $item) {
                        @is_file('.' . $item['cover']) && unlink('.' . $item['cover']);
                    }
                    $this->success('分类删除成功');
                }
            }
        }


        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'typeList' => $typeList
        ]);
    }
}
